#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC

import sys
import os
from make_var import *

templ = """/*
:name: ariane
:description: Full ariane core test
:files: {0}
:incdirs: {1}
:tags: ariane
:top_module: {2}
:timeout: 360
*/
"""

try:
    third_party_dir = os.environ['THIRD_PARTY_DIR']
    tests_dir = os.environ['TESTS_DIR']
except KeyError:
    print("Export the THIRD_PARTY_DIR and TESTS_DIR variables first")
    sys.exit(1)

try:
    tests_subdir = sys.argv[1]
except IndexError:
    print("Usage: ./generator <subdir>")
    sys.exit(1)

ariane_path = os.path.abspath(os.path.join(third_party_dir, "cores", "ariane"))
main_path = os.path.abspath(os.getcwd())
os.chdir(ariane_path)

os.environ['RISCV'] = "./"
# retrieve only data defined in makefile
M = make_vars(origin=['makefile'])

try:
    ver_cmd = M['makefile']['verilate_command']
except:
    print("Ariane makefile was changed, unable to create source list")
    sys.exit(1)

ver_cmd_comp = ver_cmd.split()
incdirs = ''
sources = ''
# flag for the next line with the top module name
get_top_module = False

for components in ver_cmd_comp:
    args = components.strip()
    if args.startswith("+incdir+"):
        incdirs += os.path.join(
            ariane_path,
            args.partition("+incdir+")[2]) + ' '
    elif args.startswith("--top-module"):
        get_top_module = True
    elif get_top_module:
        top_module = args
        get_top_module = False
    elif args.endswith('.sv'):
        # The Ariane file lists contains a reference to this file but the module itself
        # isn't instantiated anywhere. Problematically, it contains references to a
        # nonexistent interface, so it otherwise breaks elaboration. This hack can be
        # removed if the problem gets fixed upstream.
        if 'axi2apb_wrap.sv' not in args:
            sources += os.path.join(ariane_path, args) + ' '

os.chdir(main_path)
test_dir = os.path.join(tests_dir, 'generated', tests_subdir)

if not os.path.isdir(test_dir):
    os.makedirs(test_dir, exist_ok=True)

test_file = os.path.join(test_dir, "ariane.sv")

with open(test_file, "w") as f:
    f.write(templ.format(sources, incdirs, top_module))
